package version1.part2.Client.rpcClient.Impl;

import version1.part1.common.message.RpcRequest;
import version1.part1.common.message.RpcResponse;
import version1.part2.Client.RpcClient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author Stone
 * @version 1.0.1
 * @date 2025/9/19
 */
public class SimpleSocketClient implements RpcClient {

    private String host;//主机地址
    private int port;//端口号

    public SimpleSocketClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public RpcResponse sendRequest(RpcRequest request)  {
        //通过socket发送请求并得到响应
        try {
            Socket socket = new Socket(host,port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            out.writeObject(request);
            out.flush();
            RpcResponse response = (RpcResponse)in.readObject();
            return response;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
